<template>
  <div class="registerDetail">
    <van-nav-bar
      :fixed="true"
      :placeholder="true"
      :title="$route.meta.title"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <!-- 表单 -->
    <div class="formData">
      <van-form @submit="formOnSubmit" ref="form">
        <van-field
          v-model="dataSource.fixCenterName"
          name="维修中心"
          label="维修中心"
          required
          input-align="right"
          placeholder="请选择"
          right-icon="arrow"
          @click="handleSelect('fixCenterId', 'fixCenterName')"
          :rules="[{ required: true }]"
          readonly
        />

        <van-field
          v-model="dataSource.vinCode"
          name="车辆"
          label="车辆"
          input-align="right"
          placeholder="请选择"
          @click="handleSelectCar()"
          readonly
          right-icon="arrow"
        />

        <van-field
          v-model="dataSource.carNo"
          name="车牌号码"
          label="车牌号码"
          input-align="right"
          placeholder="请输入车牌号码"
          :rules="[{ required: true }]"
          :readonly="disabled"
          required
        >
          <template #button>
            <i @click="ocrCarNo" class="iconfont icon-photo"></i>
          </template>
        </van-field>

        <!-- <van-field
          v-model="dataSource.depOrgName"
          name="品牌"
          label="品牌"
          placeholder="请选择"
          input-align="right"
          right-icon="arrow"
          @click="handleSelect('depOrgId', 'depOrgName')"
          readonly
        /> -->

        <van-field
          v-model="dataSource.customerName"
          name="客户名称"
          label="客户名称"
          input-align="right"
          placeholder="请输入客户名称"
        />

        <van-field
          v-model="dataSource.customerPhone"
          name="客户联系电话"
          label="客户联系电话"
          type="tel"
          input-align="right"
          placeholder="请输入客户联系电话"
        />

        <van-field
          v-model="dataSource.ogPsnName"
          name="外服人员"
          label="外服人员"
          input-align="right"
          placeholder="请选择外服人员"
          readonly
          :rules="[{ required: true }]"
          @click="handleMoreSelect()"
          right-icon="arrow"
          required
        />
        <van-field
          v-model="dataSource.serverPersonName"
          name="服务顾问"
          label="服务顾问"
          placeholder="请选择"
          input-align="right"
          right-icon="arrow"
          @click="handleSelect('serverPersonId', 'serverPersonName')"
          readonly
        />

        <van-field
          readonly
          clickable
          name="currentDate"
          :value="dataSource.accidentDate"
          input-align="right"
          label="出险时间"
          placeholder="请选择时间"
          @click="showTimerPicker = true"
          :rules="[{ required: true }]"
          required
          v-if="!dataSource.billId"
        />
        <van-popup v-model="showTimerPicker" position="bottom">
          <van-datetime-picker
            v-model="currentDate"
            type="datetime"
            @confirm="onConfirm($event, 'accidentDate')"
            @cancel="showTimerPicker = false"
            :formatter="formatter"
          />
        </van-popup>

        <!-- <van-field
          readonly
          clickable
          name="picker"
          :value="dataSource.isRepairedName"
          label="是否推修"
          placeholder="请选择"
          input-align="right"
          @click="handleSelect('isRepaired', 'isRepairedName')"
          :rules="[{ required: true }]"
          right-icon="arrow"
        />
        <van-field
          v-model="dataSource.repairInsCmpName"
          name="推修保险公司"
          label="推修保险公司"
          placeholder="请选择"
          input-align="right"
          :rules="[{ required: true }]"
          right-icon="arrow"
          @click="handleSelect('repairInsCmpId', 'repairInsCmpName')"
          readonly
        /> -->
        <van-popup v-model="showSelectPicker" position="bottom">
          <van-field
            name="模糊查询"
            v-if="likeWhoField == 'fixCenterId'|| likeWhoField == 'serverPersonId'"
            input-align="left"
            v-model="likeWho"
            label="模糊查询"
            placeholder="请输入模糊查询关键词"
          />
          <van-picker
            show-toolbar
            :columns="columns"
            @confirm="handleSelectConfirm"
            @cancel="showSelectPicker = false"
            value-key="name"
          />
        </van-popup>

        <van-field
          value=""
          name="现场照片"
          label="现场照片"
          placeholder=""
          input-align="right"
          readonly
          required
          v-if="!dataSource.billId"
        >
          <template #button>
            <span class="imgUploadbtn" @click="wxUploadImg"
              >图片上传({{ `${fileList.length}/9` }})</span
            >
          </template>
        </van-field>
        <div class="carImgList" v-if="!dataSource.billId">
          <div
            class="carImg_item"
            v-for="(item, index) in fileList"
            :key="index"
          >
            <img @click="preImg(index)" class="carImg" :src="item.content" />
            <span @click="handleDel(index)" class="delbtn">x</span>
          </div>
        </div>

        <!-- <van-field name="uploader" label="" v-if="!dataSource.billId">
          <template #input>
            <van-uploader
              v-model="fileList"
              :max-size="5000 * 1024"
              :max-count="9"
                  capture="camera"
              :after-read="comInsFileUpload"
              @oversize="onOversize"
            >

              <van-button
                class="uploadBtn"
                @click="wxUploadImg"
                icon="plus"
                type="info"
                size="small"
              >
                图片上传
              </van-button>
            </van-uploader>
          </template>
        </van-field> -->
        <van-field
          v-model="dataSource.note"
          name="备注"
          label=""
          type="textarea"
          input-align="left"
          placeholder="备注"
          autosize
        />

        <van-field
          v-if="!dataSource.billId"
          v-model="dataSource.accidentAddress"
          name="出险地点"
          label="出险地点"
          input-align="right"
          placeholder="点击获取当前位置"
          readonly
          @click="jsdkConfig()"
          :rules="[{ required: true }]"
          required
        />
      </van-form>
      <div id="container" v-if="!dataSource.billId"></div>
      <div class="submitBtn" @click="formOnSubmit">确认</div>
    </div>
    <MultipleSelect
      :visible="showMultipleVisible"
      @close="showMultipleVisible = false"
      @multipleSubmit="multipleSubmit"
      :value="dataSource.ogPsnName"
      :list="empList"
    ></MultipleSelect>
    <div class="loading" v-if="loading">
      <van-loading size="40px" class="loadbox" color="#fff" text-color="#fff">
        提交中，请稍等...
      </van-loading>
      <div class="mask"></div>
    </div>
    <div class="loading" v-if="ocrLoading">
      <van-loading size="40px" class="loadbox" color="#fff" text-color="#fff">
        识别中，请稍等...
      </van-loading>
      <div class="mask"></div>
    </div>

    <!-- 车辆选择 -->
    <!-- <van-popup class="carPop" v-model="carVisible" position="right"> -->
    <CarList
      @close="carVisible = false"
      @getCarData="getCarData"
      :fixCenterId="dataSource.fixCenterId"
      :visible="carVisible"
    ></CarList>
    <!-- </van-popup> -->
  </div>
</template>

<script>
import {
  Search,
  Empty,
  Field,
  Form,
  Uploader,
  DatetimePicker,
  Notify,
  Toast,
  Dialog,
  Loading,
  Popup,
  ImagePreview,
} from "vant";
import MultipleSelect from "../../components/MultipleSelect/index.vue";
import outApi from "@/api/outAPi";
import commonApi from "@/api/commonApi";
import {
  getCookies,
  getFilterData,
  getCurrentDetailTime,
} from "@/utils/util.js";
import store from "@/store";
import outAPi from "../../api/outAPi";
import axios from "axios";
import CarList from "../car/index";
const base_url = process.env.BASE_API;
const map_url = process.env.MAP_URL
import qs from "qs";
import $ from "jquery";
export default {
  name: "registerDetail",
  components: {
    Search,
    Empty,
    Field,
    Form,
    Uploader,
    DatetimePicker,
    MultipleSelect,
    Notify,
    Toast,
    Dialog,
    Loading,
    Popup,
    CarList,
    ImagePreview,
  },
  data() {
    return {
      showTimerPicker: false,
      dataSource: {
        // depOrgId: '', //品牌id，String，必填
        // depOrgName: '', //品牌id，String，必填
        fixCenterId: "", //维修中心ID值,必填，String
        fixCenterName: "", //维修中心ID值,必填，String
        customerName: "", //客户名称
        customerPhone: "", //客户电话
        carId: "", //车辆id
        vinCode: "", //车架号
        carNo: "", //车牌号码 必填
        accidentDate: getCurrentDetailTime(), //出险日期
        isRepaired: "", //是否推修
        repairInsCmpId: "", //推修保险公司id
        note: "", //备注
        accidentAddress: "", //出险地点
        ogPsnName: "", //外出服务人员，多选用逗号拼接传值
        ogPsnId: "", //外出服务人员ID ,多选用逗号拼接传值
        serverPersonId: "",
        serverPersonName: "",
        userId: getCookies("userId"), //用户ID，必填，String
        latitude: 24.496074,
        longitude: 118.202965,
      },
      uploader: [],
      columns: [],
      showSelectPicker: false,
      disabled: false,
      showMultipleVisible: false,
      empList: [],
      field: "",
      fieldName: "",
      fixCenterList: [],
      brandList: [],
      userId: getCookies("userId"),
      currentDate: new Date(),
      insureList: [],
      fileList: [],
      comInsFile: "",
      serverPersonList: [],
      map: null,
      geolocation: null,
      loading: false,
      userInfo: JSON.parse(getCookies("userInfo")),
      detailId: "",
      carVisible: false,
      imgList: [],
      compressSwitch: true,
      threshold: 500,
      likeWhoField: "",
      likeWho: "",
      imgdata: "",
      ocrLoading: "",
    };
  },
  watch: {
    dataSource: {
      handler(val) {
        if (val) {
          store.commit("setAddCarInfo", val);
        }
      },
      deep: true,
    },
    "dataSource.fixCenterId": {
      handler(val) {
        if (val) {
          // this.getBrandByFixCenter();
          this.getEmpPerson();
        }
      },
      deep: true,
    },
    likeWho: function (nval, oval) {
      if (this.likeWhoField == 'fixCenterId') {
        if (nval) {
          let newArr = this.fixCenterList.filter((item) => {
            return item.name.indexOf(nval) > -1
          })
          console.log(newArr)
          this.columns = newArr
        }else{
          this.columns = this.fixCenterList
        }
      }

      if (this.likeWhoField == 'serverPersonId') {
        if (nval) {
          let newArr = this.serverPersonList.filter((item) => {
            return item.name.indexOf(nval) > -1
          })
          console.log(newArr)
          this.columns = newArr
        }else{
          this.columns = this.serverPersonList
        }
      }

    },
  },

  mounted() {
    if (localStorage.getItem("reBillId")) {
      this.detailId = localStorage.getItem("reBillId");
      this.getDetail(localStorage.getItem("reBillId"));
      document.title = "编辑跟踪单";
      this.$route.meta.title = "编辑跟踪单";
      this.getFileList(localStorage.getItem("reBillId"));
    }
    this.getMainFixCenter();

    this.getInsComList();
    this.getAccidentOrgPsnList();
    let vm = this;
    let center = new TMap.LatLng(
      vm.dataSource.latitude,
      vm.dataSource.longitude
    );
    this.map = new TMap.Map(document.getElementById("container"), {
      center: center, //设置地图中心点坐标
      zoom: 17.2, //设置地图缩放级别
      pitch: 30.5, //设置俯仰角
      rotation: 45, //设置地图旋转角度
    });
  },
  destroyed() {
    if (this.$route.path != "/registerEdit" && this.$route.path != "/car") {
      localStorage.removeItem("carData");
      localStorage.removeItem("reBillId");
      store.commit("setAddCarInfo", {});
    }
  },
  methods: {
    // ocr识别车牌
    ocrCarNo() {
      let vm = this;
      axios({
        url: `${base_url}/proxy/qywx/jsdkConfig`,
        method: "post",
        data: qs.stringify(
          { url: location.href.split("#")[0] },
          { encode: false }
        ),
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          satoken: getCookies("token"),
        },
      }).then((res) => {
        console.log("jsdkConfig:", res);
        let jsdk = res.data.data;
        localStorage.setItem("jsdk", JSON.stringify(res.data.data));
        wx.config({
          beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: jsdk.corpid, // 必填，企业微信的corpID，必须是本企业的corpID，不允许跨企业使用
          timestamp: jsdk.timestamp, // 必填，生成签名的时间戳
          nonceStr: jsdk.nonceStr, // 必填，生成签名的随机串
          signature: jsdk.signature, // 必填，签名，见 附录-JS-SDK使用权限签名算法
          jsApiList: [
            "chooseImage",
            "previewImage",
            "uploadImage",
            "downloadImage",
            "compressImage",
          ], // 必填，需要使用的JS接口列表，凡是要调用的接口都需要传进来
        });
        wx.ready(function (res) {
          wx.checkJsApi({
            jsApiList: [
              "chooseImage",
              "previewImage",
              "uploadImage",
              "downloadImage",
              "compressImage",
            ], // 需要检测的JS接口列表，所有JS接口列表见附录2,
            success: function (res) {
              console.log(res, "成功");

              wx.chooseImage({
                count: 9, // 默认9
                sizeType: ["compressed"], // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ["camera"], // 可以指定来源是相册还是相机，默认二者都有
                isSaveToAlbum: 1,
                success: function (res) {
                  vm.ocrLoading = true;

                  let localIds = res.localIds[0]; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                  wx.getLocalImgData({
                    localId: localIds, // 图片的localID
                    success: function (resp) {
                      vm.imgdata = resp.localData;
                      let formData = new FormData();

                      formData.append(
                        "file",
                        vm.base64ToFile(resp.localData, "车牌号识别照片")
                      );
                      formData.append("multiDetect", "true");
                      commonApi.plateLicense(formData).then((el) => {
                        vm.ocrLoading = false;

                        if (
                          el &&
                          el.words_result &&
                          el.words_result.length > 0
                        ) {
                          // 多个车牌号
                          if (el.words_result.length > 1) {
                            vm.fieldName = "carNo";
                            vm.showSelectPicker = true;
                            let list = [];
                            el.words_result.forEach((item, index) => {
                              list.push({
                                billId: index,
                                name: item.number,
                              });
                            });
                            vm.carNoList = list;
                            vm.columns = list;
                          } else {
                            // 单个车牌号
                            vm.dataSource.carNo = el.words_result[0].number;
                          }
                        }
                        console.log(el);
                      });
                    },
                  });
                },
                fail: function (res) {
                  console.log("失败");
                },
              });
            },
            fail(err) {
              console.log(err, "失败");
            },
            complete(opt) {
              console.log(opt, "完成");
            },
          });
        });
      });
    },

    // 图片上传
    wxUploadImg() {
      let vm = this;
      axios({
        url: `${base_url}/proxy/qywx/jsdkConfig`,
        method: "post",
        data: qs.stringify(
          // { url: 'http://bkt.autocnd.com' },
          { url: location.href.split("#")[0] },
          { encode: false }
        ),
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          satoken: getCookies("token"),
        },
      }).then((res) => {
        console.log("jsdkConfig:", res);
        let jsdk = res.data.data;
        localStorage.setItem("jsdk", JSON.stringify(res.data.data));
        wx.config({
          beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: jsdk.corpid, // 必填，企业微信的corpID，必须是本企业的corpID，不允许跨企业使用
          timestamp: jsdk.timestamp, // 必填，生成签名的时间戳
          nonceStr: jsdk.nonceStr, // 必填，生成签名的随机串
          signature: jsdk.signature, // 必填，签名，见 附录-JS-SDK使用权限签名算法
          jsApiList: [
            "chooseImage",
            "previewImage",
            "uploadImage",
            "downloadImage",
            "compressImage",
          ], // 必填，需要使用的JS接口列表，凡是要调用的接口都需要传进来
        });
        wx.ready(function (res) {
          wx.checkJsApi({
            jsApiList: [
              "chooseImage",
              "previewImage",
              "uploadImage",
              "downloadImage",
              "compressImage",
            ], // 需要检测的JS接口列表，所有JS接口列表见附录2,
            success: function (res) {
              console.log(res, "成功");
              wx.chooseImage({
                count: 9, // 默认9
                sizeType: ["compressed"], // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ["camera"], // 可以指定来源是相册还是相机，默认二者都有
                isSaveToAlbum: 1,
                success: function (res) {
                  // 多图上传遍历
                  res.localIds.forEach((item, index) => {
                    wx.getLocalImgData({
                      localId: item, // 图片的localID
                      success: function (resp) {
                        var localData = resp.localData; // localData是图片的base64数据，可以用img标签显示
                        vm.imgdata = resp.localData;
                        vm.fileList.push({
                          content: resp.localData,
                          file: vm.base64ToFile(
                            resp.localData,
                            `现场照片${index}`
                          ),
                        });
                      },
                    });
                  });
                },
                fail: function (res) {
                  console.log("失败");
                },
              });
            },
            fail(err) {
              console.log(err, "失败");
            },
            complete(opt) {
              console.log(opt, "完成");
            },
          });
        });
      });
    },

    // 图片预览
    preImg(index) {
      let arr = [];
      this.fileList.forEach((item) => {
        arr.push(item.content);
      });

      ImagePreview({
        images: arr,
        showIndex: true,
        loop: false,
        startPosition: index,
      });
    },

    // 图片删除
    handleDel(index) {
      this.fileList.splice(index, 1);
    },

    // base转换file
    base64ToFile(base64, fileName) {
      // 将base64按照 , 进行分割 将前缀  与后续内容分隔开
      let data = base64.split(",");
      // 利用正则表达式 从前缀中获取图片的类型信息（image/png、image/jpeg、image/webp等）
      let type = data[0].match(/:(.*?);/)[1];
      // 从图片的类型信息中 获取具体的文件格式后缀（png、jpeg、webp）
      let suffix = type.split("/")[1];
      // 使用atob()对base64数据进行解码  结果是一个文件数据流 以字符串的格式输出
      const bstr = window.atob(data[1]);
      // 获取解码结果字符串的长度
      let n = bstr.length;
      // 根据解码结果字符串的长度创建一个等长的整形数字数组
      // 但在创建时 所有元素初始值都为 0
      const u8arr = new Uint8Array(n);
      // 将整形数组的每个元素填充为解码结果字符串对应位置字符的UTF-16 编码单元
      while (n--) {
        // charCodeAt()：获取给定索引处字符对应的 UTF-16 代码单元
        u8arr[n] = bstr.charCodeAt(n);
      }
      // 利用构造函数创建File文件对象
      // new File(bits, name, options)
      const file = new File([u8arr], `${fileName}.${suffix}`, {
        type: type,
      });
      // 将File文件对象返回给方法的调用者
      return file;
    },

    // 地图获取
    jsdkConfig() {
      let vm = this;
      axios({
        url: `${base_url}/proxy/qywx/jsdkConfig`,
        method: "post",
        data: qs.stringify(
          // { url: 'http://bkt.autocnd.com' },
          { url: location.href.split("#")[0] },
          { encode: false }
        ),
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          satoken: getCookies("token"),
        },
      }).then((res) => {
        console.log("jsdkConfig:", res);
        let jsdk = res.data.data;
        localStorage.setItem("jsdk", JSON.stringify(res.data.data));
        wx.config({
          beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: jsdk.corpid, // 必填，企业微信的corpID，必须是本企业的corpID，不允许跨企业使用
          timestamp: jsdk.timestamp, // 必填，生成签名的时间戳
          nonceStr: jsdk.nonceStr, // 必填，生成签名的随机串
          signature: jsdk.signature, // 必填，签名，见 附录-JS-SDK使用权限签名算法
          jsApiList: [
            "openLocation",
            "getLocation",
            "chooseImage",
            "previewImage",
            "uploadImage",
            "downloadImage",
          ], // 必填，需要使用的JS接口列表，凡是要调用的接口都需要传进来
        });
        wx.ready(function (res) {
          wx.checkJsApi({
            jsApiList: [
              "openLocation",
              "getLocation",
              "chooseImage",
              "previewImage",
              "uploadImage",
              "downloadImage",
            ], // 需要检测的JS接口列表，所有JS接口列表见附录2,
            success: function (res) {
              console.log(res, "成功");
              wx.getLocation({
                type: "gcj02",
                success: function (res) {
                  console.log("获取用户位置信息成功：", res);
                  vm.dataSource.latitude = res.latitude; // 纬度
                  vm.dataSource.longitude = res.longitude; // 纬度
                  vm.txMap(res.latitude, res.longitude);
                },
                fail: function (res) {
                  console.log("获取用户位置信息失败！", res);
                },
              });
            },
            fail(err) {
              console.log(err, "失败");
            },
            complete(opt) {
              console.log(opt, "完成");
            },
          });
        });
      });
    },

    // 腾讯地图
    txMap(lat, lng) {
      let vm = this;
      const geolocation = new window.qq.maps.Geolocation(
        "4HEBZ-22MKH-OTBDM-WPN3E-HFCA2-ALB4C",
        "bkt_wx"
      );
      geolocation.getLocation((postion) => {
        console.log("腾讯地图获取的位置信息：", postion);
        if (postion.addr) {
          // console.log(console.log("详细获取位置：", postion));
          // vm.dataSource.accidentAddress = postion.addr;
        } else {
          // console.log(console.log("详细获取不到，通过ip类型获取", postion));
          // vm.dataSource.accidentAddress = postion.province + postion.city;
        }
      });
      this.map.setCenter(new TMap.LatLng(lat, lng));
      this.formatMap(lat, lng);
      //定义map变量，调用 TMap.Map() 构造函数创建地图
      // this.map = new TMap.Map(document.getElementById('container'), {
      //   center: new TMap.LatLng(lat, lng), //设置地图中心点坐标
      //   zoom: 17.2, //设置地图缩放级别
      //   pitch: 30.5, //设置俯仰角
      //   rotation: 45, //设置地图旋转角度
      // })
    },
    // 逆解析
    formatMap(lat, lng) {
      let vm = this;
      var data = {
        // location: "24.48405,118.03394",
        location: `${lat},${lng}`,
        /*换成自己申请的key*/
        key: "4HEBZ-22MKH-OTBDM-WPN3E-HFCA2-ALB4C",
        get_poi: 0,
      };
      var url = map_url
      data.output = "jsonp";

      $.ajax({
        type: "get",
        dataType: "jsonp",
        data: data,
        jsonp: "callback",
        jsonpCallback: "QQmap",
        url: url,
        success: function (json) {
          console.log("腾讯地图逆解析的地址：", json);
          if (json && json.result) {
            vm.dataSource.accidentAddress = json.result.address;
          }
        },
      });
    },

    getDetail(billId) {
      outApi
        .queyCarAccidentTrackingBillById({ billId, userId: this.userId })
        .then((res) => {
          for (const key in res.data) {
            if (res.data[key] == null || res.data[key] == undefined) {
              res.data[key] = "";
            }
          }
          this.dataSource = JSON.parse(JSON.stringify(res.data));
          this.dataSource.customerPhone = this.dataSource.mobile1;
          this.dataSource.isRepaired =
            this.dataSource.isRepaired == "是" ? 1 : 2;
          this.dataSource.isRepairedName =
            this.dataSource.isRepaired == 1 ? "是" : "否";
          this.dataSource.note = this.dataSource.remark;
          this.dataSource.repairInsCmpName = this.dataSource.repairInsCmp;
          this.dataSource.carNo = this.dataSource.carNo
            ? this.dataSource.carNo
            : this.dataSource.newCarNo;
        });
    },
    getFileList(billId) {
      commonApi.getFileList({ billId }).then((res) => {
        res.records &&
          res.records.map((item) => {
            this.fileList.push({
              url: `${base_url}/proxy/cam/file/download?attachId=${item.ATTID}&attachName=${item.ATTNAME}`,
            });
          });
      });
    },
    getCarData(data) {
      let carData = JSON.parse(JSON.stringify(data));
      this.dataSource.carId = carData.billId;
      this.dataSource.vinCode = carData.vinCode;
      this.dataSource.carNo = carData.carNo;

      this.dataSource.customerName = carData.ctmNumName
        ? carData.ctmNumName
        : "";
      this.dataSource.customerPhone = carData.ctmNumPhone
        ? carData.ctmNumPhone
        : "";
    },
    // 获取维修中心
    getMainFixCenter() {
      commonApi
        .getMainFixCenter({
          fixCenterId: "",
          userId: this.userId,
          type: "fixCenter",
        })
        .then((res) => {
          if (res.data) {
            this.fixCenterList = res.data;
            if (
              !localStorage.getItem("reBillId") ||
              localStorage.getItem("reBillId") == null
            ) {
              this.fixCenterList.forEach((item) => {
                if (localStorage.getItem("orgId") == item.billId) {
                  this.dataSource.fixCenterId = item.billId;
                  this.dataSource.fixCenterName = item.name;
                }
              });
            }

            // if (
            //   store.state.addCarInfoStore.addCarInfo &&
            //   JSON.stringify(store.state.addCarInfoStore.addCarInfo) != '{}'
            // ) {
            //   this.dataSource = store.state.addCarInfoStore.addCarInfo
            //   if (localStorage.getItem('carData')) {
            //     let carData = JSON.parse(localStorage.getItem('carData'))
            //     this.dataSource.carId = carData.billId
            //     this.dataSource.vinCode = carData.vinCode
            //     this.dataSource.carNo = carData.carNo

            //     this.dataSource.customerName = carData.ctmNumName
            //       ? carData.ctmNumName
            //       : ''
            //     this.dataSource.customerPhone = carData.ctmNumPhone
            //       ? carData.ctmNumPhone
            //       : ''
            //   }
            //   this.filterFixCenterData()
            // } else {
            //   if (localStorage.getItem('carData')) {
            //     let carData = JSON.parse(localStorage.getItem('carData'))
            //     this.dataSource.carId = carData.billId
            //     this.dataSource.vinCode = carData.vinCode
            //     this.dataSource.carNo = carData.carNo
            //   }
            // }
          }
        });
    },
    // 获取品牌
    getBrandByFixCenter() {
      commonApi
        .getBrandByFixCenter({
          fixCenterId: this.dataSource.fixCenterId,
          userId: this.userId,
        })
        .then((res) => {
          if (res.data) {
            this.brandList = res.data;
          }
        });
    },
    // 外服人员
    getAccidentOrgPsnList() {
      outAPi.getAccidentOrgPsnList({}).then((res) => {
        if (res.data) {
          let userName = this.userInfo.kdusername;
          if (!localStorage.getItem("reBillId")) {
            res.data &&
              res.data.forEach((item) => {
                if (item.name == userName) {
                  this.dataSource.ogPsnName = item.name;
                  this.dataSource.ogPsnId = item.billId;
                }
              });
          }

          this.empList = res.data;
        }
      });
    },
    // 获取服务人员
    getEmpPerson() {
      commonApi
        .getEmpPerson({
          fixCenterId: this.dataSource.fixCenterId,
          type: 'taskFollow',
        })
        .then((res) => {
          if (res.data) {
            this.serverPersonList = res.data;
          }
        });
    },
    // 保险公司
    getInsComList() {
      commonApi
        .getBaseCode({
          key: "保险公司",
          userId: this.userId,
        })
        .then((res) => {
          if (res.data) {
            this.insureList = res.data;
          }
        });
    },
    // 重新通过维修中心筛选出对应的数据
    filterFixCenterData() {
      let fixCenterData = getFilterData(
        this.fixCenterList,
        "billId",
        this.dataSource.fixCenterId
      );
      this.field = "fixCenterId";
      this.fieldName = "fixCenterName";
      this.handleSelectConfirm(fixCenterData);
    },
    // 地图初始化
    // mapInit(lng, lat, zoom) {
    //   let _this = this;
    //   // 在页面渲染完成后进行地图的实例化
    //   this.$nextTick(() => {
    //     _this.map = new TMap.Map(document.getElementById("container"), {
    //       // 地图的中心地理坐标。
    //       center: new TMap.LatLng(lat, lng),
    //       zoom: zoom,
    //     });
    //   });
    // },
    // 选择下拉
    handleSelect(field, fieldName) {
      if (this.disabled) {
        return;
      }
      this.showSelectPicker = true;
      if (field == "isRepaired") {
        this.columns = [
          { name: "是", billId: 1 },
          { name: "否", billId: 2 },
        ];
      } else if (field == "fixCenterId") {
        this.columns = this.fixCenterList;
      } else if (field == "depOrgId") {
        this.columns = this.brandList;
      } else if (field == "repairInsCmpId") {
        this.columns = this.insureList;
      } else if (field == "serverPersonId") {
        this.columns = this.serverPersonList;
      }
      this.field = field;
      this.fieldName = fieldName;
      this.likeWhoField = field;
    },
    // 选择下拉确认
    handleSelectConfirm(value, index) {
      this.dataSource[this.field] = value ? value.billId : "";
      this.dataSource[this.fieldName] = value ? value.name : "";
      if (this.field == "fixCenterId") {
        this.getBrandByFixCenter();
        this.getEmpPerson();
        // this.dataSource.carId = ''
        // this.dataSource.vinCode = ''
        // this.dataSource.carNo = ''
        // this.dataSource.customerName = ''
        // this.dataSource.customerPhone = ''
        // Notify({ type: 'warning', message: '切换维修中心请重新录入车辆信息' })
      }
      this.showSelectPicker = false;
      this.likeWho = "";
    },
    //选择车辆
    handleSelectCar() {
      this.carVisible = true;
      // this.$router.push('/car')
    },
    getLocal() {
      // console.log(1111);
    },

    onConfirm(val, field) {
      let year = val.getFullYear();
      let month = val.getMonth() + 1;
      let day = val.getDate();
      let hour = val.getHours();
      let minute = val.getMinutes();
      // let second = val.getSeconds()
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`;
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`;
      }
      // if (second >= 0 && second <= 9) { second = `0${second}` }
      this.dataSource[field] = `${year}-${month}-${day} ${hour}:${minute}:00`;
      this.showTimerPicker = false;
    },

    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      } else if (type === "day") {
        return `${value}日`;
      } else if (type === "hour") {
        return `${value}时`;
      } else if (type === "minute") {
        return `${value}分`;
      } else if (type === "second") {
        return `${value}秒`;
      }
      return value;
    },
    handleMoreSelect() {
      this.showMultipleVisible = true;
    },
    // 多选确认
    multipleSubmit(data) {
      if (data && data.length != 0) {
        this.dataSource.ogPsnName = data.map((item) => item.name).join(",");
        this.dataSource.ogPsnId = data.map((item) => item.billId).join(",");
      } else {
        this.dataSource.ogPsnName = "";
        this.dataSource.ogPsnId = "";
      }
    },
    comInsFileUpload(file, detail) {
      // this.imgPreview(file, detail.index);
      this.comInsFile = file.file;
      // return true;

      console.log("file", file);
      console.log(this.comInsFile);
      console.log(this.fileList);
    },
    // 处理图片
    async imgPreview(myFile, index) {
      const file = myFile.file;
      if (!file || !window.FileReader) {
        // 看支持不支持FileReader
        return;
      }
      const size = file.size / 1024;
      console.log(`图片大小 ===> ${size}kb`);
      console.log("图片压缩：", this.compressSwitch ? "开" : "关");
      console.log("图片压缩阈值：", this.threshold + "kb");
      console.log("图片压缩降帧值：", this.quality);
      if (
        /^image/.test(file.type) &&
        size >= this.threshold &&
        this.compressSwitch
      ) {
        const img = new Image();
        img.src = await this.getBase64(file); // 将图片将转成base64格式
        img.onload = () => {
          const data = this.compress(img, file.name, file.type);
          console.log(`压缩后 ===> ${data.fileData.size / 1024}kb`);
          this.fileList[index] = {
            content: data.base64Data,
            file: data.fileData,
          };
          myFile.status = "done";
        };
      } else {
        myFile.status = "done";
      }
    },
    // 压缩图片
    compress(img, name, type) {
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");
      // 瓦片canvas
      const tCanvas = document.createElement("canvas");
      const tctx = tCanvas.getContext("2d");
      let width = img.width;
      let height = img.height;
      // 如果图片大于四百万像素，计算压缩比并将大小压至400万以下
      let ratio;
      if ((ratio = (width * height) / 4000000) > 1) {
        ratio = Math.sqrt(ratio);
        width /= ratio;
        height /= ratio;
      } else {
        ratio = 1;
      }
      canvas.width = width;
      canvas.height = height;
      // 铺底色
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      // 如果图片像素大于100万则使用瓦片绘制
      let count;
      if ((count = (width * height) / 1000000) > 1) {
        count = ~~(Math.sqrt(count) + 1); // 计算要分成多少块瓦片
        // 计算每块瓦片的宽和高
        const nw = ~~(width / count);
        const nh = ~~(height / count);
        tCanvas.width = nw;
        tCanvas.height = nh;
        for (let i = 0; i < count; i++) {
          for (let j = 0; j < count; j++) {
            tctx.drawImage(
              img,
              i * nw * ratio,
              j * nh * ratio,
              nw * ratio,
              nh * ratio,
              0,
              0,
              nw,
              nh
            );
            ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
          }
        }
      } else {
        ctx.drawImage(img, 0, 0, width, height);
      }
      // 进行压缩
      const ndata = canvas.toDataURL("image/jpeg", this.quality);
      tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
      return {
        base64Data: ndata,
        fileData: this.dataURLtoFile(ndata, name, type),
      };
    },
    // 获取图片base64格式
    getBase64(data) {
      return new Promise((resolve, reject) => {
        const fileReader = new FileReader();
        fileReader.onload = (e) => {
          resolve(e.target.result);
        };
        fileReader.readAsDataURL(data);
        fileReader.onerror = () => {
          reject(new Error("文件流异常"));
        };
      });
    },
    // 将base64转换为文件
    dataURLtoFile(dataurl, name, type) {
      name = name || "图片";
      type = type || "jpg";
      const arr = dataurl.split(",");
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], name, {
        type: type,
      });
    },

    onOversize() {
      Toast("文件大小不能超过 5M");
    },

    uploadFiles() {
      let formData = new FormData();
      formData.append("billId", this.dataSource.billId);
      formData.append("billType", "CarAccidentTrackjngBill");

      if (this.fileList.length > 0) {
        this.fileList.forEach((item) => {
          formData.append("files", item.file);
        });
      }
      commonApi.uploadFiles(formData).then((res) => {
        Notify({ type: "success", message: "添加成功" });
        this.loading = false;
        this.$router.push("/registerList");
      });
    },

    formOnSubmit() {
      this.$refs.form
        .validate()
        .then(() => {
          if (this.fileList.length < 2) {
            Notify({ type: "danger", message: "请上传人车合影及车辆损失照片" });
            return;
          }
          console.log(this.dataSource);
          // return
          Dialog.confirm({
            title: "提示",
            message: `确定提交事故跟踪单？`,
          })
            .then(() => {
              this.loading = true;

              this.dataSource.carNo = this.dataSource.carNo.replace(/\s*/g, "");
              this.dataSource.vinCode = this.dataSource.vinCode.replace(
                /\s*/g,
                ""
              );
              if (!this.dataSource.billId) {
                outApi
                  .addnew({ ...this.dataSource, userId: this.userId })
                  .then((res) => {
                    console.log(res.data);
                    if (res.code == 0) {
                      this.loading = false;
                    }
                    this.dataSource.billId = res.data.id;
                    if (this.dataSource.billId) {
                      this.uploadFiles();
                    }
                  });
              } else {
                outApi
                  .updateCarAccidentTrackingBill({
                    ...this.dataSource,
                    serverPersonId: this.dataSource.serverPersonId
                      ? this.dataSource.serverPersonId
                      : "",
                    userId: this.userId,
                  })
                  .then((res) => {
                    console.log(res.data);
                    if (res.code != 0) {
                      Notify({ type: "success", message: "修改成功" });
                      this.$router.push("/registerList");
                    }
                    this.loading = false;

                    // this.dataSource.billId = res.data.id
                    // if (this.dataSource.billId) {
                    //   this.uploadFiles()
                    // } else {
                    //   this.$router.push('/registerList')
                    // }
                  });
              }
            })
            .catch(() => {
              console.log("取消");
            });
        })
        .catch(() => {
          this.$toast.fail("请完善信息");
        });
    },
    onClickLeft() {
      localStorage.removeItem("reBillId");
      this.$router.go(-1);
    },
  },
};
</script>

<style lang="less" scoped>
body {
  // background: #fff;
}
.flex {
  display: flex;
  align-items: center;
}
.registerDetail {
  padding-bottom: 1rem;
  background: #fff;

  .detail_header {
    justify-content: space-between;
    margin: 0.2rem 0.2rem;
    border-radius: 5px;
    background: #fff;
    padding: 0.3rem;
    .detail_header_lt {
      .carNo {
        font-size: 0.32rem;
        font-weight: bold;
        margin-bottom: 0.2rem;
        .icon-right {
          margin-left: 0.2rem;
          color: #409eff;
        }
      }
      .hank {
        font-size: 0.28rem;
        color: #666;
      }
    }
    .detail_header_rt {
      justify-content: flex-start;
      .txt {
        font-size: 0.28rem;
        color: #161616;
      }
      .icon-tel {
        color: #fff;
        background: #35bc04;
        font-size: 0.32rem;
        padding: 0.1rem;
        border-radius: 50%;
        margin-right: 0.1rem;
      }
    }
  }
  .formData {
    background: #fff;
  }
}
/deep/.van-field__error-message {
  text-align: right;
}
.submitBtn {
  background: #409eff;
  color: #fff;
  width: 75%;
  margin: auto;
  text-align: center;
  padding: 0.25rem;
  border-radius: 5px;
  margin-top: 0.6rem;
  font-size: 0.3rem;
}
#container {
  overflow: hidden;
  width: 100%;
  height: 200px;
  margin: 0;
  font-family: "微软雅黑";
}
.loading {
  position: fixed;
  width: 100%;
  height: 100%;
  .loadbox {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 11;
  }
  .mask {
    background: rgba(0, 0, 0, 0.5);
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 10;
  }
}
.imgList {
  padding: 0.2rem;
  display: flex;
  .img_item {
    margin-right: 0.2rem;
  }
}
.uploadBtn {
  // width: 80px;
  // height: 80px;
  // line-height: 80px;
  text-align: center;
}
/deep/ .van-uploader__upload {
  position: relative;
}
.icon-photo {
  font-size: 24px;
}
.imgUploadbtn {
  padding: 5px 10px;
  text-align: center;
  border-radius: 3px;
  background: #409eff;
  color: #fff;
  font-size: 12px;
  cursor: pointer;
}
.carImgList {
  padding: 0.2rem;
  // display: flex;
  // align-items: center;
  .carImg_item {
    position: relative;
    width: 80px;
    height: 80px;
    margin-right: 10px;
    float: left;
    margin-bottom: 10px;
  }
  .carImg {
    width: 80px;
    height: 80px;
  }
  .delbtn {
    position: absolute;
    top: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.8);
    color: #fff;
    padding: 2px 4px;
    z-index: 3;
    font-size: 12px;
  }
}
</style>
